# _*_ coding:utf-8 _*_
# at:2023-11-22
# author:zizle
import datetime

import requests
from urllib3 import disable_warnings

__all__ = ['ServerSystemAPI']

disable_warnings()


class ServerSystemAPI:
    HOST = 'https://210.13.218.130:9000/'

    def save_futures_contract(self, futures_contract):
        url = f'{self.HOST}v1/ruizy/variety/updateContract/'
        r = requests.post(url, json=futures_contract, verify=False)
        print('保存期货日合约完成:', r.json())

    def save_futures_main_quotes(self, sheet_id, datalist):
        if sheet_id not in [2707, 6779, 3513, 2704, 2691]:  # 动力煤和强麦的主力收盘价会为0
            datalist = list(filter(lambda x: x['datavalue'] > 0, datalist))
        if len(datalist) <= 1:
            print(datalist, f'sheet_id={sheet_id}数据已存在，无需再保存!')
        self.save_index_data(sheet_id, datalist)

    def save_index_data(self, sheet_id, datalist):
        r = requests.post(f'{self.HOST}v1/datalib/table/update/',
                          json={'dataid': sheet_id, 'row_value': datalist}, verify=False)
        return r.json().get('code')

    def get_customer_define_index_list(self):
        # 读取网络指标数据，过滤并修改起始日期
        r = requests.get(f'{self.HOST}v1/datalib/table/indexGroups/', verify=False)
        customer_indexes = None
        for g in r.json()['data']:
            if g['group'] == 'rj1':
                customer_indexes = g['data']
                break
        return customer_indexes

    def get_variety_main_contract(self, run_date: datetime.date, cover_dict: dict = None):
        url = f'{self.HOST}v1/ruizy/variety/contract/'
        query = {'m': 1, 'date': run_date.strftime('%Y-%m-%d')}
        r = requests.get(url, params=query, verify=False)
        contract_data = r.json()['data']
        main_contracts = {c['variety_en']: c['scontract'] for c in contract_data}
        # 覆盖更新合约数据
        if cover_dict:
            for k, v in cover_dict.items():
                vn, vm = k.split('.')
                if main_contracts.get(vn, '') == vm:
                    print('转换', vn, vm, '->', v)
                    main_contracts[vn] = v
        main_contracts.update(cover_dict)
        return main_contracts

    def get_index_information(self, index_id, page, page_size, use_max=True, use_day=None):
        query = {
            'iid': index_id,
            'page': page,
            'page_size': page_size
        }
        r = requests.get(f'{self.HOST}v1/datalib/table/info/', params=query, verify=False)
        resp_data = r.json()['data']
        # index_info = resp_data['index_info']
        index_data = resp_data['data']
        value = None
        if not index_data:
            return value
        if use_max:
            index_data = sorted(index_data, key=lambda x: x['datadate'], reverse=True)
            value = index_data[0]['datavalue']
        if use_day:
            value = None
            for i_data in index_data:
                if i_data['datadate'] == use_day:
                    value = i_data['datavalue']
                    break
        return value

    # 获取平值期权代码
    def get_implied_option_code(self, index_item, contracts_dict, run_date: datetime.date):
        query_day = run_date.strftime('%Y-%m-%d')
        contract = contracts_dict.get(index_item['variety_en'])
        value = self.get_index_information(index_id=index_item['ZLID'], page=1, page_size=60, use_max=True, use_day=query_day)
        if not all([contract, value]):
            print(contract, query_day, value)
            raise ValueError('没有合约或价格数据!', index_item['ZLID'], contract, value)
        # 计算期权平值
        option_value = None
        for rule in index_item['price_rules']:
            if rule['min'] < value <= rule['max']:
                option_value = int(round(value / rule['interval'], 0) * rule['interval'])
                break
        if not option_value:
            raise ValueError('平值期权代码计算错误:', option_value)
        # if index_item['variety_en'] == 'CF':  # 调整合约代码使用
        #     option_value = 17400
        # 期权代码
        option_code = f'{index_item["variety_en"]}{contract}'
        option_code += f'{index_item["interval_symbol"]}{index_item["direction"]}{index_item["interval_symbol"]}'
        option_code += f'{option_value}.{index_item["exchange"]}'
        return option_code

    def filter_unwanted_index(self, item, frequency):
        today = datetime.date.today()
        if not item['enddate']:
            return True
        value_date = datetime.datetime.strptime(item['enddate'], '%Y-%m-%d')
        if frequency == '日':
            return value_date.strftime('%Y%m%d') != today.strftime('%Y%m%d')
        elif frequency == '周':
            return value_date.strftime('%W') != today.strftime('%W')
        elif frequency == '月':  # 数据更新到上个月就不用更新
            return (int(today.strftime('%Y%m')) - int(value_date.strftime('%Y%m'))) > 1
        elif frequency == '年':  # 数据更新到上一年，就不用更新
            return (int(today.strftime('%Y')) - int(value_date.strftime('%Y'))) > 1
        else:
            return True
    def get_ths_index_list(self, frequency, fresh_new: bool = False, pointers: list = None):
        params = {
            'page': 1,
            'page_size': 9999,
            'frequency': frequency,
            'plat': 'ths'
        }
        try:
            r = requests.get(f'{self.HOST}v1/datalib/table/', params=params, verify=False)
            need_indexes = r.json()['data']['records']
        except Exception as e:
            print(f'获取需要的更新的指标数据失败了:{e}...')
            return []
        else:
            need_indexes = list(filter(lambda x: x['state'] != 0, need_indexes))
            if pointers:
                need_indexes = list(filter(lambda x: x['source_id'] in pointers, need_indexes))

            if fresh_new:
                return list(filter(lambda x: not x['refresh'], need_indexes))
            else:
                return list(filter(lambda x: self.filter_unwanted_index(x, frequency), need_indexes))  # 过滤指标

